<?php

class Admin_TextosController extends Zend_Controller_Action 
{ 
	
	private $usuario;
	private $textosDAO;
	
	protected $_acl;
	protected $_session;

	
	
	public function init() {
		$config = Zend_Registry::get ( 'config' );
		$this->_acl = $this->getFrontController()->getParam('acl');
		$this->_session = new Zend_Session_Namespace ( $config->session->namespace );
		$this->usuario = $this->_session->storage;
		$this->textosDAO = new Textos();
		$this->view->aba = 'admintextos';	
		if ( isset ( $this->usuario )) {
			$this->view->perfil = $this->usuario->perfil;
		}
	}
	
	public function preDispatch() {
	 if (!Zend_Auth::getInstance()->hasIdentity()) {
      	$this->view->logado = 0;
      	$this->_redirect('/login');
      } else {
      	$config = Zend_Registry::get ( 'config' );
      	$this->_session = new Zend_Session_Namespace ( $config->session->namespace );
		$this->_usuario = $this->_session->storage;
       	$this->view->logado = 1;
      }
	}
	
	public function indexAction() {
		
		$params = new Zend_Filter_Input(null, null, $this->getRequest()->getParams());
		$busca = $params->busca;
	
				

		if ($this->_acl->isAllowed ( $this->usuario->perfil, 'textos', 'ver' )) {
			
			if ($this->_acl->isAllowed ( $this->usuario->perfil, 'textos', 'administrar' )) {

				if ($busca) 
					$textos = $this->textosDAO->search($busca);
				 else  
					$textos = $this->textosDAO->findAll('data desc');
				
							
			} else if ($this->_acl->isAllowed ( $this->usuario->perfil, 'textos', 'ver' )) {
				
				if ($busca) 
					$textos = $this->textosDAO->search($busca, 'id desc', $this->usuario->id);
				 else  
					$textos = $this->textosDAO->findByUsuario($this->usuario->id,'id desc');
																			
			}
			
			$this->view->busca = $busca;
			$this->view->textos = $textos;
			
			
			$paginator = Zend_Paginator::factory($textos);
			
			$paginator->setItemCountPerPage(10);
			$paginator->setCurrentPageNumber($this->_getParam('page'));
			$paginator->setPageRange(range(1,10));
			Zend_View_Helper_PaginationControl::setDefaultViewPartial("_partials/paginacao.phtml");
			
			$this->view->paginator = $paginator;
			
			$this->view->textos = $textos;

			$this->view->perfil = $this->usuario->perfil;
		
		} else {
			$this->_redirect ( './' ); //Disparar erro de acesso negado
		}
	}
	
	public function inserirAction() {
		$this->view->acao = 'cadastrar';
		$this->view->areas = $this->getFormAreas();
		$this->view->grupos = $this->getFormGrupos();
		$this->view->aba = 'inserirtexto';
		$this->render('formulario');
	}
	
	public function editarAction() {
		$this->view->acao = 'editar';
		$params = new Zend_Filter_Input(null, null, $this->getRequest()->getParams());
		
		$texto = $this->textosDAO->find($params->id)->current();
		
		$this->view->areas = $this->getFormAreas($texto);
		
		$tags = array();
		$TagsTexto =  $texto->findTagsTextosByTexto();
		foreach($TagsTexto as $t) 
			$tags[] = $t->tag;		
		if (count($tags)) $this->view->tags = implode(", ",$tags);
		$this->view->texto = $texto;
		
		$this->render('formulario');
	}

	public function getFormAreas($texto='') {
		$valores = array ( );
		if ($texto) {
			foreach ( $texto->findAreasViaAreasTextosByTexto () as $t )
				$valores [] = $t->id;
		}
		
		$areasDAO = new Areas();
		$formAreas = new Zend_Form_Element_MultiCheckbox('areas');
		$formAreas->setDecorators(array(
     'Description',
		'ViewHelper',
   
    array('HtmlTag', array('tag' => '<span>')),
    array('Label', array('tag' => '<span>')),
	));
		foreach($areasDAO->fetchAll() as $a) 
			$formAreas->addMultiOptions(array($a->id => " ".$a->nome));
		$formAreas->setLabel ( "�reas de Conhecimento:" )
		->setAttrib('class', 'areas')
		->setRequired ( true )
		->setValue($valores);
		return $formAreas;
	}
	
public function getFormGrupos($texto='') {
		$valores = array ( );
		if ($texto) {
			foreach ( $texto->findTextoByGrupo() as $t )
				$valores [] = $t->id;
		}
		
		$gruposDAO = new Grupos();
		$formGrupos = new Zend_Form_Element_Select('grupos');
		$formGrupos->setDecorators(array(
     'Description',
		'ViewHelper',
    array('HtmlTag', array('tag' => '<span>')),
    array('Label', array('tag' => '<span>')),
	));
		foreach($gruposDAO->fetchAll() as $a) { 
			$formGrupos->addMultiOptions(array($a->id => " ".$a->nome));
		}
		$formGrupos->setLabel ( "Grupos:" )
		->setRequired ( true )
		->setValue($valores);
		return $formGrupos;
	}
	

	public function salvarAction() {
		
		if (! $this->getRequest ()->isPost ()) {
			return $this->_forward ( 'index' );
		}
		
		$params = new Zend_Filter_Input(null, null, $this->getRequest()->getParams());
		
		$validatorTit = new Zend_Validate();
		$validatorTit->addValidator(new Valida_NaoVazio("titulo"));
 
		$validatorTex = new Zend_Validate();
		$validatorTex->addValidator(new Valida_NaoVazio("texto"));
				
		if (!$validatorTit->isValid($params->titulo) || !$validatorTex->isValid($params->texto)) {
			print_r($validatorTit->getMessages());
			print_r($validatorTex->getMessages());
			exit();
			/* @todo Error handle */
		}
		
		$dados = array(
		'id' => $params->id,
		'titulo' => $params->titulo,
		'descricao' => $params->descricao,
		'texto' => html_entity_decode($this->view->Nl2br($params->texto)),
		'data' => Zend_Date::now()->toString("Y-M-d H:m:s"),
		'id_usuario' => $this->usuario->id,
		'tags' => trim($params->tags),
		'areas' => $params->areas
		);
	
		if ($params->id)  
			$this->textosDAO->update($dados, "id = $params->id");
		else
			$this->textosDAO->insert($dados);
									
		$this->_redirect('admintextos');
		
	}	
	

	public function apagarAction() {
		$params = new Zend_Filter_Input(null, null, $this->getRequest()->getParams());
		$this->textosDAO->delete($params->id);
		$this->_redirect("admintextos");
	}
	
	
}  